<template>
  <div class="medical-ai">
    <div class="container">
      <h1>🏥 医疗AI功能测试平台</h1>

      <el-tabs v-model="activeTab" type="card" class="ai-tabs">
        <!-- 测试AI服务连接 -->
        <el-tab-pane label="🔗 测试连接" name="connection">
          <el-card class="tab-content" shadow="never">
            <template #header>
              <h3>🔗 AI服务连接测试</h3>
            </template>
            <el-button
              type="primary"
              @click="testConnection"
              :loading="connectionLoading"
            >
              测试连接
            </el-button>
            <div
              v-if="connectionResult"
              class="result"
              :class="connectionResultClass"
            >
              {{ connectionResult }}
            </div>
          </el-card>
        </el-tab-pane>

        <!-- 分析处方内容 -->
        <el-tab-pane label="💊 处方分析" name="prescription">
          <el-card class="tab-content" shadow="never">
            <template #header>
              <h3>💊 分析处方内容</h3>
            </template>
            <el-input
              v-model="prescriptionText"
              type="textarea"
              :rows="4"
              placeholder="请输入处方内容..."
            />
            <div class="button-group">
              <el-button
                type="primary"
                @click="analyzePrescription"
                :loading="prescriptionLoading"
              >
                分析处方
              </el-button>
            </div>
            <div
              v-if="prescriptionResult"
              class="result"
              :class="prescriptionResultClass"
            >
              {{ prescriptionResult }}
            </div>
          </el-card>
        </el-tab-pane>

        <!-- 生成医疗报告 -->
        <el-tab-pane label="📋 医疗报告" name="report">
          <el-card class="tab-content" shadow="never">
            <template #header>
              <h3>📋 生成医疗报告</h3>
            </template>

            <!-- 患者信息 -->
            <div class="form-section">
              <h4>患者信息</h4>
              <el-row :gutter="20">
                <el-col :span="6">
                  <div class="input-with-label">
                    <span class="label">姓名：</span>
                    <el-input
                      v-model="reportData.patient.name"
                      placeholder="患者姓名"
                      size="small"
                      style="margin-bottom: 10px"
                    />
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="input-with-label">
                    <span class="label">年龄：</span>
                    <el-input
                      v-model.number="reportData.patient.age"
                      placeholder="年龄"
                      type="number"
                      size="small"
                      style="margin-bottom: 10px"
                    />
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="input-with-label">
                    <span class="label">性别：</span>
                    <el-select
                      v-model="reportData.patient.gender"
                      placeholder="性别"
                      size="small"
                      style="width: 100%; margin-bottom: 10px"
                    >
                      <el-option label="男" value="男" />
                      <el-option label="女" value="女" />
                    </el-select>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="input-with-label">
                    <span class="label">联系方式：</span>
                    <el-input
                      v-model="reportData.patient.phone"
                      placeholder="联系电话"
                      size="small"
                      style="margin-bottom: 10px"
                    />
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <div class="input-with-label">
                    <span class="label">既往病史：</span>
                    <el-input
                      v-model="reportData.patient.medicalHistory"
                      placeholder="既往病史"
                      size="small"
                      style="margin-bottom: 10px"
                    />
                  </div>
                </el-col>
              </el-row>
            </div>

            <!-- 订单数据 -->
            <div class="form-section">
              <h4>就诊信息</h4>
              <div class="input-tip">
                <el-icon><InfoFilled /></el-icon>
                <span
                  >请按以下格式输入，每项用换行分隔：症状描述、检查结果、诊断结果、治疗方案</span
                >
              </div>
              <el-input
                v-model="reportData.orderDataText"
                type="textarea"
                :rows="6"
                placeholder="症状描述&#10;检查结果&#10;诊断结果&#10;治疗方案"
                style="margin-bottom: 15px"
              />
            </div>

            <div class="button-group">
              <el-button
                type="primary"
                @click="generateMedicalReport"
                :loading="reportLoading"
              >
                生成报告
              </el-button>
            </div>
            <div v-if="reportResult" class="result" :class="reportResultClass">
              {{ reportResult }}
            </div>
          </el-card>
        </el-tab-pane>

        <!-- 获取诊断建议 -->
        <el-tab-pane label="🔍 诊断建议" name="diagnostic">
          <el-card class="tab-content" shadow="never">
            <template #header>
              <h3>🔍 获取诊断建议</h3>
            </template>

            <!-- 症状描述提示 -->
            <div class="input-tip">
              <el-icon><InfoFilled /></el-icon>
              <span
                >请输入患者的主要症状描述，如：头痛、发热、咳嗽、腹痛等</span
              >
            </div>
            <el-input
              v-model="symptoms"
              type="text"
              placeholder="请输入症状描述..."
              style="margin-bottom: 10px"
            />

            <!-- 病史信息提示 -->
            <div class="input-tip">
              <el-icon><InfoFilled /></el-icon>
              <span>请输入患者的病史信息，包括既往疾病、过敏史、家族史等</span>
            </div>
            <el-input
              v-model="patientHistory"
              type="textarea"
              :rows="3"
              placeholder="请输入病史信息..."
              style="margin-bottom: 15px"
            />

            <div class="button-group">
              <el-button
                type="primary"
                @click="getDiagnosticSuggestion"
                :loading="diagnosticLoading"
              >
                获取诊断建议
              </el-button>
            </div>
            <div
              v-if="diagnosticResult"
              class="result"
              :class="diagnosticResultClass"
            >
              {{ diagnosticResult }}
            </div>
          </el-card>
        </el-tab-pane>

        <!-- 检查药品相互作用 -->
        <el-tab-pane label="💊 药品相互作用" name="interaction">
          <el-card class="tab-content" shadow="never">
            <template #header>
              <h3>💊 检查药品相互作用</h3>
            </template>

            <!-- 药品列表提示 -->
            <div class="input-tip">
              <el-icon><InfoFilled /></el-icon>
              <span>请输入药品列表，每行一个药品，换行隔开</span>
            </div>
            <el-input
              v-model="drugList"
              type="textarea"
              :rows="4"
              placeholder="请输入药品列表，每行一个药品..."
            />
            <div class="button-group">
              <el-button
                type="primary"
                @click="checkDrugInteraction"
                :loading="interactionLoading"
              >
                检查相互作用
              </el-button>
            </div>
            <div
              v-if="interactionResult"
              class="result"
              :class="interactionResultClass"
            >
              {{ interactionResult }}
            </div>
          </el-card>
        </el-tab-pane>

        <!-- 生成健康建议 -->
        <el-tab-pane label="💡 健康建议" name="health">
          <el-card class="tab-content" shadow="never">
            <template #header>
              <h3>💡 生成健康建议</h3>
            </template>

            <!-- 患者信息 -->
            <div class="form-section">
              <h4>患者信息</h4>
              <el-row :gutter="20">
                <el-col :span="6">
                  <div class="input-with-label">
                    <span class="label">姓名：</span>
                    <el-input
                      v-model="healthData.patient.name"
                      placeholder="患者姓名"
                      size="small"
                      style="margin-bottom: 10px"
                    />
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="input-with-label">
                    <span class="label">年龄：</span>
                    <el-input
                      v-model.number="healthData.patient.age"
                      placeholder="年龄"
                      type="number"
                      size="small"
                      style="margin-bottom: 10px"
                    />
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="input-with-label">
                    <span class="label">性别：</span>
                    <el-select
                      v-model="healthData.patient.gender"
                      placeholder="性别"
                      size="small"
                      style="width: 100%; margin-bottom: 10px"
                    >
                      <el-option label="男" value="男" />
                      <el-option label="女" value="女" />
                    </el-select>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="input-with-label">
                    <span class="label">联系方式：</span>
                    <el-input
                      v-model="healthData.patient.phone"
                      placeholder="联系电话"
                      size="small"
                      style="margin-bottom: 10px"
                    />
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <div class="input-with-label">
                    <span class="label">既往病史：</span>
                    <el-input
                      v-model="healthData.patient.medicalHistory"
                      placeholder="既往病史"
                      size="small"
                      style="margin-bottom: 10px"
                    />
                  </div>
                </el-col>
              </el-row>
            </div>

            <!-- 订单历史 -->
            <div class="form-section">
              <h4>订单历史</h4>
              <div class="input-tip">
                <el-icon><InfoFilled /></el-icon>
                <span>请输入患者的订单历史信息，每行一个订单，换行隔开</span>
              </div>
              <el-input
                v-model="healthData.orderHistoryText"
                type="textarea"
                :rows="4"
                placeholder="请输入订单历史信息，每行一个订单..."
                style="margin-bottom: 15px"
              />
            </div>

            <div class="button-group">
              <el-button
                type="primary"
                @click="generateHealthAdvice"
                :loading="healthLoading"
              >
                生成健康建议
              </el-button>
            </div>
            <div v-if="healthResult" class="result" :class="healthResultClass">
              {{ healthResult }}
            </div>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import axios from "axios";
import { InfoFilled } from "@element-plus/icons-vue";

// 标签页状态
const activeTab = ref("connection");

// 响应式数据 - 连接测试
const connectionLoading = ref(false);
const connectionResult = ref("");
const connectionResultClass = ref("");

// 响应式数据 - 处方分析
const prescriptionLoading = ref(false);
const prescriptionResult = ref("");
const prescriptionResultClass = ref("");
const prescriptionText = ref("阿莫西林胶囊 0.5g 口服 每日3次");

// 响应式数据 - 医疗报告
const reportLoading = ref(false);
const reportResult = ref("");
const reportResultClass = ref("");
const reportData = ref({
  patient: {
    name: "张三",
    age: 45,
    gender: "男",
    phone: "13800138001",
    medicalHistory: "高血压病史3年，无其他重大疾病",
  },
  orderData: {
    symptoms: "头痛、发热",
    examination: "体温38.5℃，血压正常",
    diagnosis: "上呼吸道感染",
    treatment: "对症治疗",
  },
  orderDataText: "头痛、发热\n体温38.5℃，血压正常\n上呼吸道感染\n对症治疗",
});

// 响应式数据 - 诊断建议
const diagnosticLoading = ref(false);
const diagnosticResult = ref("");
const diagnosticResultClass = ref("");
const symptoms = ref("头痛、发热、咳嗽");
const patientHistory = ref("无"); // 新增病史信息

// 响应式数据 - 药品相互作用
const interactionLoading = ref(false);
const interactionResult = ref("");
const interactionResultClass = ref("");
const drugList = ref("阿莫西林胶囊\n布洛芬片\n维生素C片");

// 响应式数据 - 健康建议
const healthLoading = ref(false);
const healthResult = ref("");
const healthResultClass = ref("");
const healthData = ref({
  patient: {
    name: "张三",
    age: 45,
    gender: "男",
    phone: "13800138001",
    medicalHistory: "高血压病史3年，无其他重大疾病",
  },
  orderHistoryText:
    "阿莫西林胶囊 0.5g 口服 每日3次\n布洛芬片 50mg 口服 每日2次\n维生素C片 100mg 口服 每日1次",
});

// 创建专门的MedicalAI axios实例
const medicalApi = axios.create({
  baseURL: "/api", // 使用相对路径，通过Vite代理
  timeout: 10000,
  headers: {
    Accept: "text/plain",
    "Content-Type": "application/x-www-form-urlencoded",
  },
});

// 通用请求函数
async function makeRequest(endpoint: string, data: any = null) {
  try {
    console.log("发起MedicalAI API请求:", {
      endpoint,
      data,
      method: data ? "POST" : "GET",
      baseURL: "/api", // 通过Vite代理
    });

    let response;
    if (data) {
      // POST请求 - 使用URLSearchParams格式匹配application/x-www-form-urlencoded
      const formData = new URLSearchParams();
      Object.keys(data).forEach((key) => {
        formData.append(key, data[key]);
      });
      response = await medicalApi.post(endpoint, formData);
    } else {
      // GET请求
      response = await medicalApi.get(endpoint);
    }

    console.log("MedicalAI API响应:", response.data);

    // 处理响应数据
    const responseData = response.data;

    // 处理不同的响应格式
    if (responseData && typeof responseData === "object") {
      // 如果响应包含code字段（如Swagger测试的格式）
      if ("code" in responseData && responseData.code === 200) {
        return {
          success: true,
          data: responseData.data,
          message: responseData.msg,
        };
      }

      // 如果响应包含success字段
      if ("success" in responseData) {
        return responseData.success
          ? { success: true, data: responseData.data }
          : { success: false, error: responseData.message };
      }

      // 如果响应直接包含data字段
      if ("data" in responseData) {
        return { success: true, data: responseData.data };
      }

      // 其他情况，假设成功
      return { success: true, data: responseData };
    }

    // 如果响应不是对象，直接返回
    return { success: true, data: responseData };
  } catch (error: any) {
    console.error("MedicalAI API请求失败:", error);

    // 特殊处理超时错误
    if (error.code === "ECONNABORTED" || error.message.includes("timeout")) {
      return {
        success: false,
        error: `请求超时 - 请检查后端服务是否运行在端口5193上。错误详情: ${error.message}`,
      };
    }

    // 处理网络连接错误
    if (
      error.code === "ERR_NETWORK" ||
      error.message.includes("Network Error")
    ) {
      return {
        success: false,
        error: `网络连接失败 - 请检查后端服务是否启动。错误详情: ${error.message}`,
      };
    }

    // 处理CORS错误
    if (error.message.includes("CORS") || error.message.includes("cors")) {
      return {
        success: false,
        error: `跨域请求失败 - 请检查后端CORS配置。错误详情: ${error.message}`,
      };
    }

    // 处理其他错误
    return {
      success: false,
      error: `请求失败: ${error.message || error.toString()}`,
    };
  }
}

// 测试连接
async function testConnection() {
  connectionLoading.value = true;
  connectionResult.value = "正在测试连接...";
  connectionResultClass.value = "loading";

  console.log("开始测试AI服务连接...");
  console.log("目标URL: /api/MedicalAI/TestConnection (通过Vite代理)");
  console.log("请求方法: GET");

  try {
    // 使用fetch API直接测试，通过Vite代理
    console.log("使用fetch API测试连接（通过代理）...");
    const response = await fetch("/api/MedicalAI/TestConnection", {
      method: "GET",
      // 不设置任何请求头，让浏览器使用默认值
    });

    console.log("Fetch响应状态:", response.status);
    console.log("Fetch响应头:", response.headers);

    if (response.ok) {
      const data = await response.text();
      console.log("Fetch响应数据:", data);

      let successMessage = "✅ 连接成功";
      try {
        const jsonData = JSON.parse(data);
        if (jsonData.data) {
          successMessage += `\n数据: ${jsonData.data}`;
        }
        if (jsonData.msg) {
          successMessage += `\n消息: ${jsonData.msg}`;
        }
      } catch (e) {
        successMessage += `\n原始响应: ${data}`;
      }

      connectionResult.value = successMessage;
      connectionResultClass.value = "success";
      console.log("连接测试成功");
    } else {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
  } catch (error: any) {
    console.error("Fetch连接测试失败:", error);
    connectionResult.value = "❌ " + error.message;
    connectionResultClass.value = "error";
  }

  connectionLoading.value = false;
}

// 分析处方
async function analyzePrescription() {
  if (!prescriptionText.value.trim()) {
    ElMessage.warning("请输入处方内容");
    return;
  }

  prescriptionLoading.value = true;
  prescriptionResult.value = "正在分析处方...";
  prescriptionResultClass.value = "loading";

  try {
    console.log("开始分析处方...");
    console.log("目标URL: /api/MedicalAI/AnalyzePrescription");
    console.log("请求方法: POST");
    console.log("请求参数:", { prescriptionText: prescriptionText.value });

    // 使用JSON格式，增加超时时间到180秒
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 180000); // 180秒超时

    const response = await fetch("/api/MedicalAI/AnalyzePrescription", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      body: JSON.stringify({
        prescriptionText: prescriptionText.value,
      }),
      signal: controller.signal,
    });

    clearTimeout(timeoutId);
    console.log("处方分析响应状态:", response.status);

    if (response.ok) {
      const data = await response.json();
      console.log("处方分析响应数据:", data);

      if (data.code === 200) {
        prescriptionResult.value = data.data;
        prescriptionResultClass.value = "success";
        ElMessage.success("处方分析完成！");
        console.log("处方分析成功");
      } else {
        throw new Error(data.msg || "处方分析失败");
      }
    } else {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
  } catch (error: any) {
    console.error("处方分析失败:", error);

    // 特殊处理超时错误
    if (error.name === "AbortError" || error.message.includes("timeout")) {
      prescriptionResult.value =
        "❌ AI服务响应超时，请稍后重试。\n\n可能的原因：\n1. AI服务处理时间较长（可能需要3-5分钟）\n2. 网络连接较慢\n3. 服务器负载较高\n\n建议：\n- 稍后再次尝试\n- 检查网络连接\n- 联系技术支持";
      prescriptionResultClass.value = "error";
      ElMessage.error("AI服务响应超时，请稍后重试");
    } else {
      prescriptionResult.value = "❌ " + error.message;
      prescriptionResultClass.value = "error";
      ElMessage.error("处方分析失败：" + error.message);
    }
  }

  prescriptionLoading.value = false;
}

// 生成医疗报告
async function generateMedicalReport() {
  if (!reportData.value.patient.name.trim()) {
    ElMessage.warning("请输入患者姓名");
    return;
  }

  if (!reportData.value.orderDataText.trim()) {
    ElMessage.warning("请输入就诊信息");
    return;
  }

  // 解析就诊信息文本
  const orderDataLines = reportData.value.orderDataText
    .split("\n")
    .filter((line) => line.trim());
  if (orderDataLines.length < 4) {
    ElMessage.warning(
      "请完整填写就诊信息（症状描述、检查结果、诊断结果、治疗方案）"
    );
    return;
  }

  // 构建请求数据
  const requestData = {
    patient: reportData.value.patient,
    orderData: {
      symptoms: orderDataLines[0] || "",
      examination: orderDataLines[1] || "",
      diagnosis: orderDataLines[2] || "",
      treatment: orderDataLines[3] || "",
    },
  };

  reportLoading.value = true;
  reportResult.value = "正在生成医疗报告...";
  reportResultClass.value = "loading";

  try {
    console.log("开始生成医疗报告...");
    console.log("目标URL: /api/MedicalAI/GenerateMedicalReport");
    console.log("请求方法: POST");
    console.log("请求参数:", requestData);

    // 使用JSON格式，增加超时时间到180秒
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 180000); // 180秒超时

    const response = await fetch("/api/MedicalAI/GenerateMedicalReport", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      body: JSON.stringify(requestData),
      signal: controller.signal,
    });

    clearTimeout(timeoutId);
    console.log("医疗报告响应状态:", response.status);

    if (response.ok) {
      const data = await response.json();
      console.log("医疗报告响应数据:", data);

      if (data.code === 200) {
        reportResult.value = data.data;
        reportResultClass.value = "success";
        ElMessage.success("医疗报告生成完成！");
        console.log("医疗报告生成成功");
      } else {
        throw new Error(data.msg || "医疗报告生成失败");
      }
    } else {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
  } catch (error: any) {
    console.error("医疗报告生成失败:", error);

    // 特殊处理超时错误
    if (error.name === "AbortError" || error.message.includes("timeout")) {
      reportResult.value =
        "❌ AI服务响应超时，请稍后重试。\n\n可能的原因：\n1. AI服务处理时间较长（可能需要3-5分钟）\n2. 网络连接较慢\n3. 服务器负载较高\n\n建议：\n- 稍后再次尝试\n- 检查网络连接\n- 联系技术支持";
      reportResultClass.value = "error";
      ElMessage.error("AI服务响应超时，请稍后重试");
    } else {
      reportResult.value = "❌ " + error.message;
      reportResultClass.value = "error";
      ElMessage.error("医疗报告生成失败：" + error.message);
    }
  }

  reportLoading.value = false;
}

// 获取诊断建议
async function getDiagnosticSuggestion() {
  if (!symptoms.value.trim()) {
    ElMessage.warning("请输入症状描述");
    return;
  }

  if (!patientHistory.value.trim()) {
    ElMessage.warning("请输入病史信息");
    return;
  }

  diagnosticLoading.value = true;
  diagnosticResult.value = "正在获取诊断建议...";
  diagnosticResultClass.value = "loading";

  try {
    console.log("开始获取诊断建议...");
    console.log("目标URL: /api/MedicalAI/GetDiagnosticSuggestion");
    console.log("请求方法: POST");
    console.log("请求参数:", {
      symptoms: symptoms.value,
      patientHistory: patientHistory.value,
    });

    // 使用JSON格式，增加超时时间到180秒
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 180000); // 180秒超时

    const response = await fetch("/api/MedicalAI/GetDiagnosticSuggestion", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      body: JSON.stringify({
        symptoms: symptoms.value,
        patientHistory: patientHistory.value,
      }),
      signal: controller.signal,
    });

    clearTimeout(timeoutId);
    console.log("诊断建议响应状态:", response.status);

    if (response.ok) {
      const data = await response.json();
      console.log("诊断建议响应数据:", data);

      if (data.code === 200) {
        diagnosticResult.value = data.data;
        diagnosticResultClass.value = "success";
        ElMessage.success("诊断建议获取完成！");
        console.log("诊断建议获取成功");
      } else {
        throw new Error(data.msg || "诊断建议获取失败");
      }
    } else {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
  } catch (error: any) {
    console.error("诊断建议获取失败:", error);

    // 特殊处理超时错误
    if (error.name === "AbortError" || error.message.includes("timeout")) {
      diagnosticResult.value =
        "❌ AI服务响应超时，请稍后重试。\n\n可能的原因：\n1. AI服务处理时间较长（可能需要3-5分钟）\n2. 网络连接较慢\n3. 服务器负载较高\n\n建议：\n- 稍后再次尝试\n- 检查网络连接\n- 联系技术支持";
      diagnosticResultClass.value = "error";
      ElMessage.error("AI服务响应超时，请稍后重试");
    } else {
      diagnosticResult.value = "❌ " + error.message;
      diagnosticResultClass.value = "error";
      ElMessage.error("诊断建议获取失败：" + error.message);
    }
  }

  diagnosticLoading.value = false;
}

// 检查药品相互作用
async function checkDrugInteraction() {
  if (!drugList.value.trim()) {
    ElMessage.warning("请输入药品列表");
    return;
  }

  // 将文本域的值转换为数组格式
  const drugArray = drugList.value
    .split("\n")
    .map((drug) => drug.trim())
    .filter((drug) => drug.length > 0);

  if (drugArray.length === 0) {
    ElMessage.warning("请输入有效的药品列表");
    return;
  }

  interactionLoading.value = true;
  interactionResult.value = "正在检查药品相互作用...";
  interactionResultClass.value = "loading";

  try {
    console.log("开始检查药品相互作用...");
    console.log("目标URL: /api/MedicalAI/CheckDrugInteractions");
    console.log("请求方法: POST");
    console.log("请求参数:", { drugList: drugArray });

    // 使用JSON格式，增加超时时间到180秒
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 180000); // 180秒超时

    const response = await fetch("/api/MedicalAI/CheckDrugInteractions", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      body: JSON.stringify({
        drugList: drugArray,
      }),
      signal: controller.signal,
    });

    clearTimeout(timeoutId);
    console.log("药品相互作用响应状态:", response.status);

    if (response.ok) {
      const data = await response.json();
      console.log("药品相互作用响应数据:", data);

      if (data.code === 200) {
        interactionResult.value = data.data;
        interactionResultClass.value = "success";
        ElMessage.success("药品相互作用检查完成！");
        console.log("药品相互作用检查成功");
      } else {
        throw new Error(data.msg || "药品相互作用检查失败");
      }
    } else {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
  } catch (error: any) {
    console.error("药品相互作用检查失败:", error);

    // 特殊处理超时错误
    if (error.name === "AbortError" || error.message.includes("timeout")) {
      interactionResult.value =
        "❌ AI服务响应超时，请稍后重试。\n\n可能的原因：\n1. AI服务处理时间较长（可能需要3-5分钟）\n2. 网络连接较慢\n3. 服务器负载较高\n\n建议：\n- 稍后再次尝试\n- 检查网络连接\n- 联系技术支持";
      interactionResultClass.value = "error";
      ElMessage.error("AI服务响应超时，请稍后重试");
    } else {
      interactionResult.value = "❌ " + error.message;
      interactionResultClass.value = "error";
      ElMessage.error("药品相互作用检查失败：" + error.message);
    }
  }

  interactionLoading.value = false;
}

// 生成健康建议
async function generateHealthAdvice() {
  if (!healthData.value.patient.name.trim()) {
    ElMessage.warning("请输入患者姓名");
    return;
  }

  if (!healthData.value.orderHistoryText.trim()) {
    ElMessage.warning("请输入订单历史信息");
    return;
  }

  // 将订单历史文本转换为数组格式
  const orderHistoryArray = healthData.value.orderHistoryText
    .split("\n")
    .map((order) => order.trim())
    .filter((order) => order.length > 0);

  if (orderHistoryArray.length === 0) {
    ElMessage.warning("请输入有效的订单历史信息");
    return;
  }

  // 构建请求数据
  const requestData = {
    patient: healthData.value.patient,
    orderHistory: orderHistoryArray,
  };

  healthLoading.value = true;
  healthResult.value = "正在生成健康建议...";
  healthResultClass.value = "loading";

  try {
    console.log("开始生成健康建议...");
    console.log("目标URL: /api/MedicalAI/GenerateHealthAdvice");
    console.log("请求方法: POST");
    console.log("请求参数:", requestData);

    // 使用JSON格式，增加超时时间到180秒
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 180000); // 180秒超时

    const response = await fetch("/api/MedicalAI/GenerateHealthAdvice", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      body: JSON.stringify(requestData),
      signal: controller.signal,
    });

    clearTimeout(timeoutId);
    console.log("健康建议响应状态:", response.status);

    if (response.ok) {
      const data = await response.json();
      console.log("健康建议响应数据:", data);

      if (data.code === 200) {
        healthResult.value = data.data;
        healthResultClass.value = "success";
        ElMessage.success("健康建议生成完成！");
        console.log("健康建议生成成功");
      } else {
        throw new Error(data.msg || "健康建议生成失败");
      }
    } else {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
  } catch (error: any) {
    console.error("健康建议生成失败:", error);

    // 特殊处理超时错误
    if (error.name === "AbortError" || error.message.includes("timeout")) {
      healthResult.value =
        "❌ AI服务响应超时，请稍后重试。\n\n可能的原因：\n1. AI服务处理时间较长（可能需要3-5分钟）\n2. 网络连接较慢\n3. 服务器负载较高\n\n建议：\n- 稍后再次尝试\n- 检查网络连接\n- 联系技术支持";
      healthResultClass.value = "error";
      ElMessage.error("AI服务响应超时，请稍后重试");
    } else {
      healthResult.value = "❌ " + error.message;
      healthResultClass.value = "error";
      ElMessage.error("健康建议生成失败：" + error.message);
    }
  }

  healthLoading.value = false;
}

// 组件挂载时自动测试连接
onMounted(() => {
  testConnection();
});
</script>

<style scoped>
.medical-ai {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  background: white;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

h1 {
  color: #2c3e50;
  text-align: center;
  margin-bottom: 30px;
  font-size: 28px;
  font-weight: 600;
}

.ai-tabs {
  margin-top: 20px;
}

.ai-tabs :deep(.el-tabs__header) {
  margin-bottom: 20px;
}

.ai-tabs :deep(.el-tabs__nav-wrap) {
  padding: 0;
}

.ai-tabs :deep(.el-tabs__item) {
  font-size: 14px;
  font-weight: 500;
  padding: 0 20px;
  height: 40px;
  line-height: 40px;
  border-radius: 6px 6px 0 0;
  transition: all 0.3s ease;
}

.ai-tabs :deep(.el-tabs__item.is-active) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.ai-tabs :deep(.el-tabs__item:hover) {
  background-color: #f0f2f5;
  color: #409eff;
}

.tab-content {
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #fafafa;
}

.tab-content :deep(.el-card__header) {
  background-color: #f8f9fa;
  border-bottom: 1px solid #ddd;
}

.tab-content h3 {
  color: #34495e;
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.tab-content :deep(.el-card__body) {
  padding: 20px;
}

.button-group {
  margin-top: 15px;
  margin-bottom: 15px;
}

.result {
  margin-top: 15px;
  padding: 15px;
  background-color: #ecf0f1;
  border-radius: 4px;
  white-space: pre-wrap;
  font-family: "Courier New", monospace;
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #ddd;
}

.result.loading {
  color: #7f8c8d;
  font-style: italic;
  background-color: #f8f9fa;
}

.result.error {
  color: #e74c3c;
  background-color: #fdf2f2;
  border: 1px solid #f5c6cb;
}

.result.success {
  color: #27ae60;
  background-color: #f0f9f0;
  border: 1px solid #c3e6c3;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 20px;
    margin: 10px;
  }

  h1 {
    font-size: 24px;
  }

  .ai-tabs :deep(.el-tabs__item) {
    font-size: 12px;
    padding: 0 10px;
  }

  .tab-content :deep(.el-card__body) {
    padding: 15px;
  }
}

/* 表单样式 */
.form-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.form-section h4 {
  color: #495057;
  margin: 0 0 15px 0;
  font-size: 16px;
  font-weight: 600;
  border-bottom: 2px solid #007bff;
  padding-bottom: 5px;
}

.form-section:last-child {
  margin-bottom: 0;
}

.input-tip {
  display: flex;
  align-items: center;
  color: #606266;
  font-size: 14px;
  margin-bottom: 10px;
}

.input-tip .el-icon {
  margin-right: 5px;
  color: #909399;
}

/* 新增样式 */
.input-with-label {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.input-with-label .label {
  font-size: 14px;
  color: #555;
  margin-right: 10px;
  white-space: nowrap; /* 防止文字换行 */
  min-width: 60px; /* 增加最小宽度确保标签不换行 */
  flex-shrink: 0; /* 防止标签被压缩 */
}
</style>